package redis

import "fmt"

type StreamMsg struct {
	Id     string
	Data   map[string][]byte
	Fields []string
}

func ParseXReadResult(r Result) (result map[string][]*StreamMsg, err error) {
	vals, err := r.Values()
	if err != nil {
		return nil, err
	}
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("%s", fmt.Sprint(e))
		}
	}()
	result = map[string][]*StreamMsg{}
	for _, vKey := range vals {
		vKeyRows := vKey.([]any)
		msgs := []*StreamMsg{}
		for _, vMsg := range vKeyRows[1].([]any) {
			vMsgRows := vMsg.([]any)
			msg := &StreamMsg{Id: string(vMsgRows[0].([]byte)), Data: map[string][]byte{}, Fields: []string{}}
			var field string
			for _, v := range vMsgRows[1].([]any) {
				if field == "" {
					field = string(v.([]byte))
				} else {
					msg.Data[field] = v.([]byte)
					msg.Fields = append(msg.Fields, field)
					field = ""
				}
			}
			msgs = append(msgs, msg)
		}
		result[string(vKeyRows[0].([]byte))] = msgs
	}
	return
}
